package com.run2code.idea.plugin.codegenerate.biz.generate.service.impl;

import com.google.common.base.CaseFormat;
import com.intellij.openapi.project.Project;
import com.run2code.idea.plugin.codegenerate.biz.db.bizdata.Mapper;
import com.run2code.idea.plugin.codegenerate.biz.db.bizdata.Entity;
import com.run2code.idea.plugin.codegenerate.biz.db.metadata.Column;
import com.run2code.idea.plugin.codegenerate.biz.db.metadata.Field;
import com.run2code.idea.plugin.codegenerate.biz.db.metadata.Table;
import com.run2code.idea.plugin.codegenerate.biz.db.utils.JavaType;
import com.run2code.idea.plugin.codegenerate.biz.generate.content.CodeGenContext;
import com.run2code.idea.plugin.codegenerate.biz.generate.service.AbstractCodeGenerator;

import java.util.ArrayList;
import java.util.List;
/**
 * 默认生成策略
 * 关注公众号【奔跑的码畜】，一起进步不迷路
 *
 * @author 第七人格
 * @date 2023/10/30
 */
public class CodeGeneratorImpl extends AbstractCodeGenerator {

    @Override
    protected void doGenerate(Project project, CodeGenContext codeGenContext) {

        List<Table> tables = codeGenContext.getTables();
        for (Table table : tables) {
            List<Column> columns = table.getColumns();
            List<Field> fields = new ArrayList<>();

            for (Column column : columns) {
                Field field = new Field(column.getComment(), JavaType.convertType(column.getType()), column.getName());
                field.setId(column.isId());
                fields.add(field);
            }

            // 生成Entity
            Entity entity = new Entity(table.getComment(), codeGenContext.getEntityPackage() + CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, table.getName()), table.getName(), fields);
            // 生成Mapper
            Mapper mapper = new Mapper(table.getComment(), codeGenContext.getXmlDir() + "I" + CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, table.getName()) + "Mapper", entity);

            writeFile(project, codeGenContext.getEntityPackage(), entity.getSimpleName() + ".java", "entity.ftl", entity, Boolean.TRUE);
            writeFile(project, codeGenContext.getMapperPackage(), mapper.getSimpleName() + ".java", "dao.ftl", mapper, Boolean.TRUE);
            writeFile(project, codeGenContext.getXmlDir(), mapper.getModel().getSimpleName() + "Mapper.xml", "mapper.ftl", mapper, Boolean.TRUE);

        }

    }

}
